﻿using System;
using Dapper;
using SilenthinkContract.Domain;

namespace SilenthinkService
{
    internal static partial class SqlTemplate
    {
        internal static class LogTemplate
        {
            #region AppError
            internal static SqlBuilder.Template GetAppError(int id)
            {
                var builder = new SqlBuilder().Field("*")
                    .Table(DatabaseSchema.LogSchema.Table.AppError)
                    .Where("[Id]=@Id", new { id });
                return builder.AddTemplate(BasicSingleTableSqlTemplate.SelectTopOne);
            }
            internal static SqlBuilder.Template TruncateAppError()
            {
                var builder = new SqlBuilder()
                    .Table(DatabaseSchema.LogSchema.Table.AppError);

                return builder.AddTemplate("truncate table /**table**/");
            }
            internal static SqlBuilder.Template GetPagedAppError(int index = 1, int size = 20, byte level = 0, string machineIp = null, string userName = null, string clientIp = null)
            {
                CheckIndexSize(ref index, ref size);
                var builder = new SqlBuilder().Field("[Id],[Machine],[Server],[ServerIp],[Level],[ExType],[ExSource],[ExMessage],[ClientIp],[CreatedBy],[CreatedOn]")
                .Table(DatabaseSchema.LogSchema.Table.AppError)
                .OrderBy("id desc")
                .AddParameters(new { begin = (index - 1) * size + 1, end = index * size });
                if (level > 0)
                {
                    builder.Where("[Level]=@Level", new { level });
                }
                if (!string.IsNullOrEmpty(machineIp))
                {
                    builder.Where("([Machine]=@MachineIp OR [ServerIp]=@MachineIp)", new { machineIp });
                }
                if (!string.IsNullOrEmpty(userName))
                {
                    builder.Where("[CreatedBy]=@CreatedBy", new { CreatedBy = userName });
                }
                if (!string.IsNullOrEmpty(clientIp))
                {
                    builder.Where("[ClientIp]=@ClientIp", new { clientIp });
                }
                return builder.AddTemplate(BasicSingleTableSqlTemplate.PagedSelect);
            }

            #endregion
        }
    }
}